package com.example.day10;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.ContactsContract;
import android.provider.Telephony;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    Button button101,button2,button3,button4,button5;
    ListView listView;
    MyAdapter myAdapter;
    ArrayList<Map<String, Object>> list;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button101 = findViewById(R.id.button1);
        button2=findViewById(R.id.button2);
        button3=findViewById(R.id.button3);
        button4=findViewById(R.id.button4);
        button5=findViewById(R.id.button5);
        listView = findViewById(R.id.list1);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                readMy(1);
            }
        });
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                readMy(2);
            }
        });
        button5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                readMy(3);
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkAccess( Manifest.permission.READ_SMS,2);

            }
        });
        button101.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkAccess( Manifest.permission.READ_CONTACTS,1);
            }
        });
    }
    private void checkAccess(String access,int code){
        //Manifest.permission.READ_EXTERNAL_STORAGE
        //检查当前权限（若没有该权限，值为-1；若有该权限，值为0）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int hasAccess = ContextCompat.checkSelfPermission(getApplication(), access);
            Log.e("PERMISION_CODE", hasAccess + "***");
            if (hasAccess == PackageManager.PERMISSION_GRANTED) {
                // TODO: 2019/6/15 获得授权执行操作
                if(code==1){
                    readUser();
                }else if(code==2){
                    readSMS();
                }

            } else {
                ActivityCompat.requestPermissions(this, new String[]{access}, code);
            }
        }else{
            // TODO: 2019/6/15 非6.0直接使用
            if(code==1){
                readUser();
            }else if(code==2){
                readSMS();
            }
        }
    }

    //用户选择是否同意授权后，会回调这个方法
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        第1个参数，请求码，对应上述方法的第3个参数；
//        第2个参数，请求权限数组；
//        第3个参数，请求权限的结果数组。
            if (permissions[0].equals(Manifest.permission.READ_CONTACTS) && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // TODO: 2019/6/15 获得授权执行操作
//http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&page=1
                if(requestCode==1){
                    readUser();
                }else if(requestCode==2){
                    readSMS();
                }
            } else {
                // TODO: 2019/6/15 未获得授权执行的操作
                finish();

            }

    }



    private void  readUser(){
        //TODO 1:获得ContentResolver
        ContentResolver resolver = getContentResolver();
        //TODO 2:确定uri和要查询的字段
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String[] strs = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                         ContactsContract.CommonDataKinds.Phone.NUMBER,"phonebook_label"};
        //TODO 3:执行查询并将结果遍历展现在ListView中和存储到本地的数据库中
        Cursor cursor = resolver.query(uri, strs, null, null, null);
        list = new ArrayList<>();
        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex("phonebook_label"));
            name = name+cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            Map<String, Object> map = new HashMap<>();
            map.put("name", name);
            map.put("phoneNUM", number);
            list.add(map);
        }
        myAdapter = new MyAdapter(MainActivity.this,list);
        listView.setAdapter(myAdapter);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void readSMS() {
        ContentResolver resolver = getContentResolver();
        Uri uri= Telephony.Sms.CONTENT_URI;
        String[] strs={Telephony.Sms.BODY,Telephony.Sms.ADDRESS};
        Cursor cursor=resolver.query(uri,strs,null,null,null);

        list = new ArrayList<>();
        while(cursor.moveToNext()){
            String address=cursor.getString(cursor.getColumnIndex(Telephony.Sms.ADDRESS));
            String body=cursor.getString(cursor.getColumnIndex(Telephony.Sms.BODY));
            Map<String, Object> map = new HashMap<>();
            map.put("name", address);
            map.put("phoneNUM", body);
            list.add(map);
            //执行insert语句
        }
        myAdapter = new MyAdapter(MainActivity.this,list);
        listView.setAdapter(myAdapter);
    }

    public void readMy(int flag){
        int hasAccess = ContextCompat.checkSelfPermission(getApplication(), "com.bawei.guwei.READ");
        if(hasAccess==0){
            Uri uri=Uri.parse("content://com.guwei");
            ContentResolver contentResolver=getContentResolver();
            switch(flag){
                case 1:
                    query(uri,contentResolver);
                    break;
                case 2:
                    delete(uri,contentResolver);
                    break;
                case 3:
                    insert(uri,contentResolver);
                    break;
            }
        }else{
            Toast.makeText(this,"木有授权"+hasAccess,Toast.LENGTH_SHORT).show();
        }



    }

    public void query(Uri uri,ContentResolver contentResolver){
        //参数一：uri 参数二：查询的字段 参数三：条件  参数四：为?赋值 参数五：排序

        Cursor cursor=contentResolver.query(uri,new String[]{"Name","sex","Age"},null,null,null);
       if (cursor==null){

           Log.e("#####","空的~~");
       }else
        Log.e("#####???",cursor.getCount()+"");
        int aa=0;
        list = new ArrayList<>();
        while(cursor.moveToNext()){
            aa++;
            String address=cursor.getString(cursor.getColumnIndex("Name"));
            String body=cursor.getString(cursor.getColumnIndex("Age"));
            String age=cursor.getString(cursor.getColumnIndex("sex"));
            Map<String, Object> map = new HashMap<>();
            map.put("name", address);
            map.put("phoneNUM", body+" "+age);
            list.add(map);
            //执行insert语句
        }

        myAdapter = new MyAdapter(MainActivity.this,list);
        listView.setAdapter(myAdapter);
    }
    public  void delete(Uri uri,ContentResolver contentResolver){
        //参数一：uri  参数二：条件 参数三：为?赋值
        int raw=contentResolver.delete(uri,"name=?",new String[]{"5红孩儿"});
        query(uri,contentResolver);
    }
    public void insert(Uri uri,ContentResolver contentResolver){
        //添加数据 Name,sex,Age
        ContentValues contentValues=new ContentValues();
        contentValues.put("Name","王国桦");
        contentValues.put("Age",8);
        contentValues.put("sex","女");
        contentResolver.insert(uri,contentValues);
        query(uri,contentResolver);
    }

}
